using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Decav.Gatsb;
using Decav.Gatsb.Data;
using Decav.Gatsb.Application;
using System.Web.UI.MobileControls;
using System.Collections.Generic;
using Decav.Gatsb.Web;
using Decav.Geocoding;

public partial class ClarifyLocations : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        noMappedLocationCheck.Attributes["onclick"] = "ShowHideLocationText(this.selected)";
        errorRibbonDiv.Visible = false;
        selectLocationErrorDiv.Visible = false;
        enterLocationPara.Style[HtmlTextWriterStyle.Display] = noMappedLocationCheck.Checked ? "none" : "block";

        if (!IsPostBack && !IsCallback)
        {
            Initialize();
        }
    }

    private void Initialize()
    {
        using (IGatsbDataAdapter adapt = GatsbApplication.Current.GetDataAdapter())
            Locations = adapt.GetUserIncompleteLocations();

        placesList.DataSource = Locations;
        placesList.DataBind();


        if (Locations.Length == 0)
        {
            Response.Redirect("~/Home.aspx", true);
        }
        else
        {
            CurrentLocation = Locations[0];
        }
    }

    private void InitializeCurrentLocation()
    {
        nameTextBox.Text = CurrentLocation.Name;
        typeDropDown.SelectedIndex = 0;
        locationTextBox.Text = string.Empty;
        mainPages.MoveTo(gatherInfoStep);
        locationSelectedHidden.Value = string.Empty;
        locationFinishedInfo.Visible = !CurrentLocation.Temporary;
    }

    protected Location[] Locations
    {
        get
        {
            return ViewState["Locations"] as Location[];
        }
        set
        {
            ViewState["Locations"] = value;
        }
    }

    protected Location CurrentLocation
    {
        get
        {
            return ViewState["CurrentLocation"] as Location;
        }
        set
        {
            ViewState["CurrentLocation"] = value;
            InitializeCurrentLocation();
        }
    }

    protected Location DidYouMeanLocation
    {
        get
        {
            return ViewState["DidYouMeanLocation"] as Location;
        }
        set
        {
            ViewState["DidYouMeanLocation"] = value;
        }
    }

    /// <summary>
    /// Gets the type selected for the <see cref="CurrentLocation"/>.
    /// </summary>
    public LocationType SelectedType
    {
        get
        {
            return (LocationType)Enum.Parse(typeof(LocationType), typeDropDown.SelectedValue);
        }
    }

    protected void PlacesList_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        Guid locationId = new Guid(e.CommandArgument.ToString());

        foreach (Location l in Locations)
        {
            if (l.Id == locationId)
            {
                CurrentLocation = l;
                break;
            }
        }
    }

    protected string GetLocationImage(Location location)
    {
        return location.Temporary ? "Images/Pushpins/6.gif" : "Images/Pushpins/1.gif";
    }

    protected void mainPages_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        WizardStepBase nextStep = mainPages.WizardSteps[e.NextStepIndex];

        if (nextStep == selectLocationStep)
        {
            e.Cancel = !MoveToSelectLocation();
        }
        else if (nextStep == finishedStep)
        {
            e.Cancel = !MoveToFinish();
        }
    }

    private bool MoveToFinish()
    {
        if (locationSelectedHidden.Value.Trim().Length == 0 && !noMappedLocationCheck.Checked)
        {
            selectLocationErrorDiv.Visible = true;
            selectLocationErrorDiv.InnerText = "Select a location to setup this location, or press 'previous' to change your search.";
            return false;
        }


        Guid selectedLocationId = Guid.Empty;
            
        if (!noMappedLocationCheck.Checked)
            selectedLocationId = new Guid(locationSelectedHidden.Value);


        Location selectedLocation = null;
        using (IGatsbDataAdapter adapt = GatsbApplication.Current.GetDataAdapter())
        {
            if (!noMappedLocationCheck.Checked)
            {
                selectedLocation = adapt.GetLocation(selectedLocationId);
                CurrentLocation.Address = selectedLocation.Address;
                CurrentLocation.Locale = selectedLocation.Locale;
                CurrentLocation.GeographicCoordinates = selectedLocation.GeographicCoordinates;
            }
            else
            {
                CurrentLocation.Locale = GatsbApplication.Current.CurrentLocale;
                CurrentLocation.GeographicCoordinates = Decav.Geography.LatLongPoint.Empty;
            }

            CurrentLocation.Type = SelectedType;
            CurrentLocation.Name = nameTextBox.Text;
            CurrentLocation.Temporary = false;

            adapt.UpdateLocation(CurrentLocation);
        }

        for (int i = 0; i < Locations.Length; i++)
        {
            if (Locations[i].Id == CurrentLocation.Id)
            {
                Locations[i] = CurrentLocation;
                break;
            }
        }

        UpdateTempList();
        return true;
    }

    private bool MoveToSelectLocation()
    {
        if (noMappedLocationCheck.Checked)
        {
            MoveToFinish();
            mainPages.MoveTo(finishedStep);
        }

        curLocationMap.Pushpins.Clear();

        #region Match by name
        // TODO: Complete this part, need to add the "did you mean..."
        List<Location> matchByName = new List<Location>();
        //List<Location> matchByName = new List<Location>(GatsbApplication.Current.FindLocation(
        //    LocationSearchCriteria.Parse(nameTextBox.Text)));

        foreach (Location l in matchByName)
        {
            if (l.Id == CurrentLocation.Id)
            {
                matchByName.Remove(l);
                break;
            }
        }

        if (matchByName.Count > 0)
        {
            DidYouMeanLocation = matchByName[0];

            didYouMeanDiv.Visible = true;
            didYouMeanLink.Text = string.Format("Were you looking for {0} ({1})?  Click here to choose that location.",
                DidYouMeanLocation.Name, DidYouMeanLocation.Address.ToString());
        }
        else
        {
            DidYouMeanLocation = null;
            didYouMeanDiv.Visible = false;
        }
        #endregion

        #region Match by location

        Location[] matchByLocation = GatsbApplication.Current.FindLocation(
            LocationSearchCriteria.Parse(locationTextBox.Text));

        #endregion

        #region Configure Map
        curLocationMap.Pushpins.Clear();

        if (DidYouMeanLocation != null)
            curLocationMap.Pushpins.Add(new MapPushpin(DidYouMeanLocation.Id,
                DidYouMeanLocation.Name, DidYouMeanLocation.GeographicCoordinates));

        foreach (Location l in matchByLocation)
        {
            if (l.Temporary)
                continue;

            if (DidYouMeanLocation != null && l.Id == DidYouMeanLocation.Id)
                continue;

            curLocationMap.Pushpins.Add(new MapPushpin(l.Id, l.Name, l.GeographicCoordinates));
        }

        if (curLocationMap.Pushpins.Count > 0)
            curLocationMap.MapCenter = curLocationMap.Pushpins[0].Point;

        #endregion

        locationsFoundRepeater.DataSource = matchByLocation;
        locationsFoundRepeater.DataBind();

        if (matchByName.Count > 0 || matchByLocation.Length > 0)
        {
            return true;
        }
        else
        {
            errorRibbonDiv.Visible = true;
            errorRibbonDiv.InnerText = "We could not find any locations matching your search.";
            return false;
        }
    }

    private void UpdateTempList()
    {
        placesList.DataSource = Locations;
        placesList.DataBind();
    }

    protected int GetLocationPushpinIndex(Location location)
    {
        foreach (MapPushpin pp in curLocationMap.Pushpins)
        {
            if (pp.Id == location.Id)
                return Math.Max(curLocationMap.Pushpins.IndexOf(pp), 6);
        }

        return 6;
    }

    protected string GetLocationJavascript(Location location)
    {
        if (location.Temporary)
        {
            return string.Format("alert(\"This location is new and doesn't have an address yet.\");return false;");
        }
        else
        {
            return string.Format("CenterMap({0}, {1});return false;", location.GeographicCoordinates.Latitude, location.GeographicCoordinates.Longitude);
        }
    }

    protected void DidYouMeanLink_Click(object sender, EventArgs e)
    {
    }

    protected void mainPages_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        foreach (Location loc in Locations)
        {
            if (loc.Temporary)
            {
                CurrentLocation = loc;
                return;
            }
        }

        Response.Redirect("~/Home.aspx", true);
    }
}
